﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PPIDesktopClient.Entities;
using System.Windows.Forms;
using PPIDesktopClient.General;
using PPIDesktopClient.General;
using System.IO;
using System.ComponentModel;

namespace PPIDesktopClient.Controls.Downloader
{
    public class DownloadSpecificImagesUtility : UserControl
    {
        protected int m_TotalImages = 0;
        protected bool m_Stopped = false;
        private DevComponents.DotNetBar.ButtonX buttonX1;

        private EBaseAsset m_structure = null;

        public event EventHandler<CompletedEventArgs> FinishedUpload;
        protected void OnFinishedUpload(object o, CompletedEventArgs e)
        {
            // Safely invoke an event:
            if (FinishedUpload != null)
            {
                FinishedUpload(o, e);
            }
        }

        public DownloadSpecificImagesUtility()
        {
            InitializeComponent();
            HideShowControls(false);
        }

        protected delegate void HideShowControlsCallback(bool status);

        protected void HideShowControls(bool status)
        {
            if (this.InvokeRequired)
            {
                HideShowControlsCallback d = new HideShowControlsCallback(HideShowControls);
                this.Invoke(d, new object[] { status });
            }
            else
            {
                foreach (Control c in this.Controls)
                {
                    c.Visible = status;
                }
            }
        }

        private void m_BackgroundWorkerDownloader_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker bw = (BackgroundWorker)sender;
            if (bw.CancellationPending)
            {
                e.Cancel = true;
            }
            Download(e);

        }

        private void Download(DoWorkEventArgs e)
        {
            List<EBaseImage> _ImageList = m_structure.Images;
            HideShowControls(true);
            CalculateAmountImages(_ImageList);
            int _CountImages = m_TotalImages;
            
            foreach (EBaseImage _Image in m_structure.Images)
            {
                if (m_BackgroundWorkerDownloader.CancellationPending)
                {
                    e.Cancel = true;
                    return;
                }
                byte[] _ByteImage;
                FileInfo _DestinationFile = EBaseImage.GetImageFile(_Image.GetAsset().Id, _Image.FileName);
                if (!_DestinationFile.Exists)
                {
                    _ByteImage = _Image.GetImageBytes();
                    ImagesHelper.CreateImageFromBytes(_ByteImage, _DestinationFile.FullName);
                }
                _CountImages--;
                m_BackgroundWorkerDownloader.ReportProgress(ReportProgress(_CountImages));

            }
        }

        private int ReportProgress(int _CountUploaded)
        {
            int _Progress;
            try
            {
                _Progress = ((m_TotalImages - _CountUploaded) * 100) / m_TotalImages;
            }
            catch (Exception)
            {
                _Progress = 0;
            }
            return _Progress;
        }

        private void CalculateAmountImages(List<EBaseImage> _ImageList)
        {
            string _DestinationImagePath;
            foreach (EBaseImage  _Image in _ImageList)
            {
                if (!EBaseImage.GetImageFile(_Image.Asset.Id, _Image.FileName).Exists)
                {
                    m_TotalImages++;
                }
            }
        }

        private void m_BackgroundWorkerDownloader_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            int countUploaded = (((((e.ProgressPercentage * m_TotalImages) / 100) - m_TotalImages) * -1) - m_TotalImages) * -1;
            if (countUploaded != m_TotalImages)
                countUploaded++;
            lblShowStats.Text = (countUploaded) + " / " + m_TotalImages.ToString();

            progressBarDownloader.Value = e.ProgressPercentage;
        }

        private void m_BackgroundWorkerDownloader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            progressBarDownloader.Value = 0;
            m_TotalImages = 0;
            lblShowStats.Text = "";
            if (!e.Cancelled)
            {
                HideShowControls(false);
                OnFinishedUpload(this, new CompletedEventArgs(m_structure.Id));
            }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            //if (m_Stopped)
            //    StartDownload();
            //else
            //    StopDownload();
        }

        public void StartDownload(EUtility_Asset_XMissionStructure structure)
        {
            if (!m_BackgroundWorkerDownloader.IsBusy)
            {
                m_structure = structure;
                m_BackgroundWorkerDownloader.RunWorkerAsync();
                m_Stopped = false;
            }

        }

        public void StopDownload()
        {
            m_BackgroundWorkerDownloader.CancelAsync();
            m_Stopped = !m_Stopped;
            if (m_Stopped)
                this.btnStop.Image = global::PPIDesktopClient.Properties.Resources.Play;
            else
                this.btnStop.Image = global::PPIDesktopClient.Properties.Resources.Stop;

        }

        private void InitializeComponent()
        {
            this.m_BackgroundWorkerDownloader = new System.ComponentModel.BackgroundWorker();
            this.progressBarDownloader = new DevComponents.DotNetBar.Controls.ProgressBarX();
            this.lblShowStats = new DevComponents.DotNetBar.LabelX();
            this.labelX1 = new DevComponents.DotNetBar.LabelX();
            this.btnStop = new DevComponents.DotNetBar.ButtonX();
            this.SuspendLayout();
            // 
            // m_BackgroundWorkerDownloader
            // 
            this.m_BackgroundWorkerDownloader.WorkerReportsProgress = true;
            this.m_BackgroundWorkerDownloader.WorkerSupportsCancellation = true;
            this.m_BackgroundWorkerDownloader.DoWork += new System.ComponentModel.DoWorkEventHandler(this.m_BackgroundWorkerDownloader_DoWork);
            this.m_BackgroundWorkerDownloader.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.m_BackgroundWorkerDownloader_RunWorkerCompleted);
            this.m_BackgroundWorkerDownloader.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.m_BackgroundWorkerDownloader_ProgressChanged);
            // 
            // progressBarDownloader
            // 
            this.progressBarDownloader.Location = new System.Drawing.Point(170, 0);
            this.progressBarDownloader.Name = "progressBarDownloader";
            this.progressBarDownloader.Size = new System.Drawing.Size(90, 15);
            this.progressBarDownloader.TabIndex = 0;
            this.progressBarDownloader.Text = "progressBarX1";
            // 
            // lblShowStats
            // 
            this.lblShowStats.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.lblShowStats.Location = new System.Drawing.Point(93, 0);
            this.lblShowStats.Name = "lblShowStats";
            this.lblShowStats.Size = new System.Drawing.Size(45, 15);
            this.lblShowStats.TabIndex = 8;
            // 
            // labelX1
            // 
            this.labelX1.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.labelX1.Location = new System.Drawing.Point(0, 0);
            this.labelX1.Name = "labelX1";
            this.labelX1.Size = new System.Drawing.Size(87, 15);
            this.labelX1.TabIndex = 7;
            this.labelX1.Text = "Downloading Images";
            // 
            // btnStop
            // 
            this.btnStop.AccessibleRole = System.Windows.Forms.AccessibleRole.PushButton;
            this.btnStop.ColorTable = DevComponents.DotNetBar.eButtonColor.OrangeWithBackground;
            this.btnStop.Image = global::PPIDesktopClient.Properties.Resources.Stop;
            this.btnStop.Location = new System.Drawing.Point(266, 0);
            this.btnStop.Name = "btnStop";
            this.btnStop.Size = new System.Drawing.Size(16, 15);
            this.btnStop.TabIndex = 9;
            this.btnStop.Click += new System.EventHandler(this.btnStop_Click);
            // 
            // Downloader
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.Transparent;
            this.Controls.Add(this.btnStop);
            this.Controls.Add(this.lblShowStats);
            this.Controls.Add(this.labelX1);
            this.Controls.Add(this.progressBarDownloader);
            this.Name = "Downloader";
            this.Size = new System.Drawing.Size(299, 16);
            this.ResumeLayout(false);

        }
        private System.ComponentModel.BackgroundWorker m_BackgroundWorkerDownloader;
        private DevComponents.DotNetBar.Controls.ProgressBarX progressBarDownloader;
        private DevComponents.DotNetBar.LabelX lblShowStats;
        private DevComponents.DotNetBar.LabelX labelX1;
        private DevComponents.DotNetBar.ButtonX btnStop;


    }
}
